layui.use(["table", "jquery", "layer", "form", "upload"], function () {
    var table = layui.table;
    var form = layui.form;
    var layer = layui.layer;
    var $ = layui.jquery;
    // console.log(params_id);
    table.render({
        elem: "#test",
        url: "/file/dire/" + params_id,
        toolbar: "#toolbarDemo",
        height: layui_table_view__height,
        defaultToolbar: ["filter", "print"],
        id: "top_table",
        data: [],
        parseData: function (res) {
            //res 即为原始返回的数据
            var result;
            // console.log(res);

            // console.log(result);
            return {
                code: 0, //解析接口状态
                msg: "成功", //解析提示文本
                count: res.total, //解析数据长度
                data: res.rows, //解析数据列表
            };
        },
        cols: [
            [
                {field: 'indent', width: 80, title: 'ID', sort: true, hide: true}
                , {field: 'fileNumber', width: 180, title: '档号', sort: true}
                , {field: 'fondNumber', title: '全宗号', hide: true}
                , {field: 'archiveCode', title: '档案馆代码', hide: true}
                , {field: 'recodeNumber', title: '档案号', hide: true}
                , {field: 'certNumber', title: '证字号', event: 'setSign'}
                , {field: 'correctTitle', title: '正题名'}
                , {field: 'maleGender', title: '男性别', hide: true}
                , {field: 'maleName', title: '男姓名'}
                , {field: 'maleIdNumber', title: '男身份证', hide: true}
                , {field: 'malebirth', title: '男出生日期', hide: true}
                , {field: 'maleOrigMaritalStatus', title: '男方原婚姻状态', hide: true}
                , {field: 'maleCertType', title: '男方证件类型', hide: true}
                , {field: 'maleIdType', title: '男方身份类型', hide: true}
                , {field: 'maleNationality', title: '男方国籍', hide: true}
                , {field: 'maleNation', title: '男方民族', hide: true}
                , {field: 'maleLocation', title: '男方常住户口所在地', hide: true}
                , {field: 'maleCertNumber', title: '男方证件印制号', hide: true}
                , {field: 'femaleGender', title: '女性别', hide: true}
                , {field: 'femaleName', title: '女姓名'}
                , {field: 'femaleIdNumbe', title: '女身份证号', hide: true}
                , {field: 'femalebirth', title: '女出生日期', hide: true}
                , {field: 'femaleOrigMaritalStatus', title: '女方原婚姻状态', hide: true}
                , {field: 'femaleCertType', title: '女方证件类型', hide: true}
                , {field: 'femaleIdType', title: '女方身份类型', hide: true}
                , {field: 'femaleNationality', title: '女方国籍', hide: true}
                , {field: 'femaleNation', title: '女方民族', hide: true}
                , {field: 'femaleLocation', title: '女方常住户口所在地', hide: true}
                , {field: 'femaleCertNumber', title: '女方证件印制号', hide: true}
                , {field: 'registAuthority', title: '登记机关', hide: true}
                , {field: 'origRegistAuthority', title: '原登记机关', hide: true}
                , {field: 'origRegistDate', title: '原登记日期', hide: true}
                , {field: 'underAgency', title: '承办机关', hide: true}
                , {field: 'registName', title: '登记员姓名', hide: true}
                , {field: 'delNot', title: '是否删除', hide: true}
                , {field: 'maritalCertRemark', title: '结婚证备注', hide: true}
                , {field: 'divorceCertRemark', title: '离婚证备注', hide: true}
                , {field: 'origMaritalRegistDate', title: '原结婚登记日期', hide: true}
                , {field: 'otherRemark', title: '其他备注', hide: true}
                , {field: 'businessType', title: '业务类型', hide: true}
                , {field: 'year', title: '年度', hide: true}
                , {field: 'marryDate', title: '结婚日期', hide: true}
                , {field: 'registDate', title: '登记日期', hide: true}
                , {field: 'maleMarryType', title: '男方结婚类型', hide: true}
                , {field: 'femaleMarryType', title: '女方结婚类型', hide: true}


                // , { fixed: "right", title: "操作", toolbar: "#barDemo-2", width: 180 },
                , {fixed: "right", title: "操作", toolbar: "#barDemo", width: 180},
            ],
        ],
        page: {
            //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
            limit: 10, //一页显示多少条
            limits: [5, 10, 15, 20, 25, 30], //每页条数的选择项
            last: "尾页", //不显示尾页
        },
    });

    //头工具栏事件
    table.on("toolbar(test)", function (obj) {
        var checkStatus = table.checkStatus(obj.config.id);
        switch (obj.event) {
            case "search_Test":
                let tr_arr = $(
                    "[lay-id='top_table'] .layui-table-body.layui-table-main tr"
                );
                let search_value = $("#test_Reload__input").val();
                search_value = search_value.trim();
                // console.log(tr_arr,search_value);
                for (let index = 0; index < tr_arr.length; index++) {
                    let text_arr = [];

                    let tr_index = tr_arr.eq(index);

                    for (let inner = 0; inner < tr_index.children().length; inner++) {
                        let td_index = tr_index.children().eq(inner).text();
                        td_index = td_index.trim();
                        text_arr.push(td_index);
                    }

                    // console.log(text_arr);
                    let have = false;
                    for (let index = 0; index < text_arr.length; index++) {
                        const text = text_arr[index];

                        if (text.indexOf(search_value) > -1) {
                            have = true;
                        }

                        if (index + 1 == text_arr.length && !have) {
                            tr_index.css("display", "none");
                        } else {
                            tr_index.css("display", "");
                        }
                    }
                }

                break;
            case "showAll":
                layer.confirm("是否显示全部？", {icon: 3, title: "提示"}, function (
                    index
                ) {
                    table.reload(
                        "top_table",
                        {
                            page: {
                                curr: 1, //重新从第 1 页开始
                            },
                            where: {},
                        },
                        "data"
                    );
                    layer.close(index);
                });

                break;
            case "addNew":
                let editIndex = layer.open({
                    type: 1,
                    title: "添加",
                    maxmin: true,
                    area: "600px",
                    content: TABLE_HTML.top_add_tableEditHtml,
                });
                $(document).one("click", "#top_add_test_edit__form", function () {
                    let d = {};
                    let t = $("#popForm-3 [name]").serializeArray();
                    $.each(t, function () {
                        d[this.name] = this.value;
                    });
                    d.direId = params_id;
                    d.type = 0;

                    // if (!d.fileNumber || !d.fileTitle) {
                    if (!d.fileNumber) {
                        layer.msg("档案号或文件标题不能为空！");
                        return false;
                    }
                    console.log(d);
                    $.ajax({
                        url: "/file",
                        type: "POST",
                        data: d,
                        success: function (rep) {
                            console.log(rep);
                            if (rep.status == 200) {
                                layer.msg("添加成功！");
                                table.reload(
                                    "top_table",
                                    {
                                        page: {
                                            curr: 1, //重新从第 1 页开始
                                        },
                                        where: {},
                                    },
                                    "data"
                                );
                                layer.close(editIndex);
                            } else {
                                layer.msg("添加失败！");
                                console.error(rep);
                            }
                        },
                        error: function (error) {
                            console.warn(error.statusText);
                        },
                    });
                    return false;
                });
                $(document).one("click", "#top_add_test_edit__form_init", function () {
                    layer.confirm("是否重置？", function (index) {
                        // form.val("popFromId-3", initData);
                        document.getElementById("popForm-3").reset();
                        layer.close(index);
                    });
                });
                break;
            case "upload_top":
                $("#upload_top").click();
                // layer.msg("上传成功！");

                break;
            case "multi_upload":
                mul_index = layer.open({
                    type: 1,
                    title: "多文件上传",
                    content: $("#multi_upload"),
                    area: ["50%", "60%"],
                    // closeBtn: 1,
                    cancel: function () {
                        success_upload_file_number = 0;
                        file_number = 0;
                        // layer.close(mul_index);
                        $("#multi_upload__List")[0].innerHTML = "";
                    },
                });
                break;
        }
    });

    //监听行工具事件
    table.on("tool(test)", function (obj) {
        var data = obj.data;
        switch (obj.event) {
            case "edit":
                // console.log(data);
                let initData = {};
                // 编辑框的默认值
                initData = {
                    indent: data.indent,
                    fileNumber: data.fileNumber,
                    fondNumber: data.fondNumber,
                    archiveCode: data.archiveCode,
                    recodeNumber: data.recodeNumber,
                    certNumber: data.certNumber,
                    correctTitle: data.correctTitle,
                    maleGender: data.maleGender,
                    maleName: data.maleName,
                    maleIdNumber: data.maleIdNumber,
                    malebirth: data.malebirth,
                    maleOrigMaritalStatus: data.maleOrigMaritalStatus,
                    maleCertType: data.maleCertType,
                    maleIdType: data.maleIdType,
                    maleNationality: data.maleNationality,
                    maleNation: data.maleNation,
                    maleLocation: data.maleLocation,
                    maleCertNumber: data.maleCertNumber,
                    femaleGender: data.femaleGender,
                    femaleName: data.femaleName,
                    femaleIdNumbe: data.femaleIdNumbe,
                    femalebirth: data.femalebirth,
                    femaleOrigMaritalStatus: data.femaleOrigMaritalStatus,
                    femaleCertType: data.femaleCertType,
                    femaleIdType: data.femaleIdType,
                    femaleNationality: data.femaleNationality,
                    femaleNation: data.femaleNation,
                    femaleLocation: data.femaleLocation,
                    femaleCertNumber: data.femaleCertNumber,
                    registAuthority: data.registAuthority,
                    origRegistAuthority: data.origRegistAuthority,
                    origRegistDate: data.origRegistDate,
                    underAgency: data.underAgency,
                    registName: data.registName,
                    delNot: data.delNot,
                    maritalCertRemark: data.maritalCertRemark,
                    origMaritalRegistDate: data.origMaritalRegistDate,
                    otherRemark: data.otherRemark,
                    businessType: data.businessType,
                    year: data.year,
                    marryDate: data.marryDate,
                    registDate: data.registDate,
                    maleMarryType: data.maleMarryType,
                    femaleMarryType: data.femaleMarryType,
                    divorceCertRemark: data.divorceCertRemark
                };
                let editIndex = layer.open({
                    type: 1,
                    title: "编辑",
                    maxmin: true,
                    area: "600px",
                    content: TABLE_HTML.top_tableEditHtml,
                    success: function () {
                        form.val("popFromId", initData);
                    },
                    cancel: function () {
                        for (const key in initData) {
                            initData[key] = '';
                        }
                    }
                });
                $(document).one("click", "#top_test_edit__form", function () {
                    let d = {};
                    let t = $("#popForm [name]").serializeArray();
                    $.each(t, function () {
                        d[this.name] = this.value;
                    });
                    // console.log(d);

                    // if (!d.fileNumber || !d.fileTitle) {
                    if (!d.fileNumber) {
                        layer.msg("档案号或文件标题不能为空！");
                        return false;
                    }
                    $.ajax({
                        url: "/file",
                        type: "PUT",
                        data: d,
                        success: function (rep) {
                            console.log(rep);
                            if (rep.status == 200) {
                                layer.msg("编辑成功！");
                                table.reload(
                                    "top_table",
                                    {
                                        page: {
                                            curr: 1, //重新从第 1 页开始
                                        },
                                        where: {},
                                    },
                                    "data"
                                );
                                layer.close(editIndex);
                            } else {
                                layer.msg("编辑失败！");
                                console.error(rep);
                            }
                        },
                        error: function (error) {
                            console.warn(error.statusText);
                        },
                    });
                    return false;
                });
                $(document).one("click", "#top_test_edit__form_init", function () {
                    layer.confirm("是否重置？", function (index) {
                        form.val("popFromId", initData);
                        layer.close(index);
                    });
                });
                break;
            case "del":
                layer.confirm("确认删除？", function (index) {
                    let isCurrent = data.fileNumber == current_fileNumber ? true : false;
                    $.ajax({
                        url: "/file/" + data.id,
                        headers: {
                            authToken: sessionStorage.getItem("authToken"),
                        },
                        type: "DELETE",
                        success: function (rep) {
                            console.log(rep);
                            if (rep.status == 200) {
                                layer.msg("删除成功！");
                                table.reload(
                                    "top_table",
                                    {
                                        page: {
                                            curr: 1, //重新从第 1 页开始
                                        },
                                        where: {},
                                    },
                                    "data"
                                );
                                if (isCurrent && sessionStorage.getItem("__fileType") == 1) {
                                    table.reload(
                                        "bottom_table",
                                        {
                                            url: "/file/dire/fileNumber/" + current_fileNumber,
                                            where: {},
                                        },
                                        "data"
                                    );
                                    layer.close(index);
                                }
                            } else {
                                layer.msg("编辑失败！");
                                console.error(rep);
                            }
                        },
                        error: function (error) {
                            layer.msg(error);
                            console.warn(error.statusText);
                        },
                    });
                    layer.close(index);
                });
                break;
            case "view":
                const __fileType = sessionStorage.getItem("__fileType");
                switch (__fileType) {
                    case "1":
                        current_fileNumber = data.fileNumber;
                        table.reload(
                            "bottom_table",
                            {
                                url: "/file/dire/fileNumber/" + current_fileNumber,
                            },
                            "data"
                        );
                        break;
                    case "0":
                        if (!data.including) {
                            layer.msg("无文件！");
                            return;
                        }
                        var url = data.filePath.trim();
                        var host = location.host;

                        layer.open({
                            type: 1,
                            title: data.fileTitle,
                            maxmin: true,
                            area: ["50%", "100%"],
                            content: `<iframe src="/web/viewer.html?file=http://${host}${url}"frameborder="0" style="width:100%;height:99%;"></iframe>`,
                        });
                        break;
                }
                break;
        }
    });

    //监听行单击事件
    // table.on("row(test)", function (obj) {
    //   console.log(obj)
    //   const __fileType = sessionStorage.getItem("__fileType");
    //   current_fileNumber = obj.data.fileNumber;
    //   switch (__fileType) {
    //     case "1":
    //       table.reload(
    //           "bottom_table",
    //           {
    //             url: "/file/dire/fileNumber/" + current_fileNumber,
    //           },
    //           "data"
    //       );
    //       break;
    //     case "0":
    //       if (!obj.data.including) {
    //         layer.msg("无文件！！");
    //         return;
    //       }
    //       var url = obj.data.filePath.trim();
    //       var host = location.host;
    //
    //       layer.open({
    //         type: 1,
    //         title: obj.data.fileTitle,
    //         maxmin: true,
    //         area: ["50%", "100%"],
    //         content: `<iframe src="/web/viewer.html?file=http://${host}${url}"frameborder="0" style="width:100%;height:99%;"></iframe>`,
    //       });
    //       break;
    //   }
    // });


    table.on("test", function (obj) {
        console.log(obj)
        const __fileType = sessionStorage.getItem("__fileType");
        current_fileNumber = obj.data.fileNumber;

        if (obj.event === 'setSign') {
            switch (__fileType) {
                case "1":
                    table.reload(
                        "bottom_table",
                        {
                            url: "/file/dire/fileNumber/" + current_fileNumber,
                        },
                        "data"
                    );
                    break;
                case "0":
                    if (!obj.data.including) {
                        layer.msg("无文件！！");

                        return;
                    }
                    var url = obj.data.filePath.trim();
                    var host = location.host;

                    layer.open({
                        type: 1,
                        title: obj.data.fileTitle,
                        maxmin: true,
                        area: ["50%", "100%"],
                        content: `<iframe src="/web/viewer.html?file=http://${host}${url}"frameborder="0" style="width:100%;height:99%;"></iframe>`,
                    });
                    break;
            }
        }
    });


});
